package com.ks.utils.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * 
 * @author pks
 * @date 2020年7月9日
 */
public class SUtilXml {
	/***
     *XML格式字符串转换成MAP
     * @param xml
     * @return
     */
    public static Map xmlToMap(String xml) {
        try {
        	Map result = new HashMap();
            Document document = DocumentHelper.parseText(xml);
            Element nodeElement = document.getRootElement();
            String rootName = nodeElement.getQName().getName();
            List node = nodeElement.elements();
            Map map = new HashMap();
            List<Map> list = new ArrayList<Map>();
            for (Iterator it = node.iterator(); it.hasNext(); ) {
                Element elm = (Element) it.next();
                Map childMap = childs(elm.asXML());
                List<Object> temp = new ArrayList<Object>();
                if(map.containsKey(elm.getName())){
                	temp = (List<Object>) map.get(elm.getName());
                }
        		if(childMap != null && !childMap.isEmpty()){
        			temp.add(childMap);
        			map.put(elm.getName(), temp);
    			}else{
    				if(StringUtils.isNotBlank(elm.getText())){
    					map.put(elm.getName(), elm.getText());
    				}
    			}
            }
            node = null;
            nodeElement = null;
            document = null;
            result.put(rootName, map);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static Map childs(String xml) throws DocumentException{
    	Map map = new HashMap();
    	Document document = DocumentHelper.parseText(xml);
    	Element nodeElement = document.getRootElement();
    	List node = nodeElement.elements();
    	for (Iterator it = node.iterator(); it.hasNext(); ) {
    		Element elm = (Element) it.next();
    		Map childMap = childs(elm.asXML());
    		List<Object> temp = new ArrayList<Object>();
            if(map.containsKey(elm.getName())){
            	temp = (List<Object>) map.get(elm.getName());
            }
    		if(childMap != null && !childMap.isEmpty()){
    			temp.add(childMap);
    			map.put(elm.getName(), temp);
			}else{
				if(StringUtils.isNotBlank(elm.getText())){
					map.put(elm.getName(), elm.getText());
				}
			}
		}
    	
		return map;
    }
}
